package com.kit.data.kitopeso.tools;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

public class NumUtils {

    public static String filterDigits(String input) {
        if (input == null) {
            return "0";
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            char c = input.charAt(i);
            if (Character.isDigit(c) || c == '.') {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    public static String formatToTwoDecimals(double value) {
        DecimalFormat df = new DecimalFormat("#");
        return df.format(value);
    }

    public static double roundToTwoDecimals(double value) {
        return new BigDecimal(value)
                .setScale(2, RoundingMode.HALF_UP)
                .doubleValue();
    }

    @SuppressLint("DefaultLocale")
    public static String formatString(double value) {
        return String.format("%.2f", value);
    }


    public static int str2Int(String data) {
        if (!TextUtils.isEmpty(data)) {
            try {
                return Integer.parseInt(data);
            } catch (NumberFormatException e) {
                return 0;
            }
        }
        return 0;
    }

    public static double str2Double(String data) {
        if (!TextUtils.isEmpty(data)) {
            try {
                return Double.parseDouble(data);
            } catch (NumberFormatException e) {
                return 0;
            }
        }
        return 0;
    }

}
